package com.duoec.magichour.core.web.freemarker.pipe.common;

import com.duoec.magichour.core.web.freemarker.pipe.Pipe;
import freemarker.core.BasePipeWithParams;
import freemarker.core.Environment;
import freemarker.template.SimpleScalar;
import freemarker.template.TemplateModel;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by ycoe on 16/5/9.
 */
@Pipe("time_before")
public class TimeBeforePipe extends BasePipeWithParams {
    @Override
    protected TemplateModel exec(Environment env, List arguments) {
        final long time = getNumber(env).longValue();
        if (time == 0) {
            return new SimpleScalar("");
        }
        String format = "yyyy.M.d";
        if (arguments != null && !arguments.isEmpty()) {
            format = ((SimpleScalar) arguments.get(0)).getAsString();
        }
        String interval = getTimeBeforeString(time, format);
        return new SimpleScalar(interval);
    }

    public String getTimeBeforeString(long time, String format) {
        String interval;
        long now = System.currentTimeMillis();
        long timeSpan = now - time;
        if (timeSpan / 1000 < 10 && timeSpan / 1000 >= 0) {
            //如果时间间隔小于10秒则显示“刚刚”time/10得出的时间间隔的单位是秒
            interval = "刚刚";
        } else if (timeSpan / 1000 < 60 && timeSpan / 1000 > 0) {
            //如果时间间隔小于60秒则显示多少秒前
            int se = (int) ((timeSpan % 60000) / 1000);
            interval = se + "秒前";
        } else if (timeSpan / 60000 < 60 && timeSpan / 60000 > 0) {
            //如果时间间隔小于60分钟则显示多少分钟前
            int m = (int) ((timeSpan % 3600000) / 60000);//得出的时间间隔的单位是分钟
            interval = m + "分钟前";
        } else if (timeSpan / 3600000 < 24 && timeSpan / 3600000 >= 0) {
            //如果时间间隔小于24小时则显示多少小时前
            int h = (int) (timeSpan / 3600000);//得出的时间间隔的单位是小时
            interval = h + "小时前";
        } else if (timeSpan / 3600000 / 24 < 3 && timeSpan / 3600000 / 24 >= 1) {
            //如果时间间隔大于1天，小于3天
            int d = (int) (timeSpan / 3600000 / 24);//得出的时间间隔的单位是天
            interval = d + "天前";
        } else {
            //大于24小时，则显示正常的时间，但是不显示秒
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            interval = sdf.format(new Date(time));
        }
        return interval;
    }

}
